import tkinter as tk

# 定义按钮点击事件
def button_click(event):
   text = event.widget.cget("text")
   if text == "=":
       try:
           result = eval(entry.get())
           entry.delete(0, tk.END)
           entry.insert(tk.END, str(result))
       except Exception as e:
           entry.delete(0, tk.END)
           entry.insert(tk.END, "Error")
   elif text == "C":
       entry.delete(0, tk.END)
   elif text == "DEL":
       entry.delete(len(entry.get()) - 1, tk.END)
   elif text == "BCK":
       entry.delete(0, tk.END)
   else:
       entry.insert(tk.END, text)

# 创建主窗口
root = tk.Tk()
root.title("Calculator")

# 设置计算器显示区
entry = tk.Entry(root, width=20, font=('Arial', 16), justify='right')
entry.grid(row=0, column=0, columnspan=4, padx=5, pady=5)

# 按钮的标签
buttons = [
   'C', 'DEL', 'BCK', '/',
   '7', '8', '9', '*',
   '4', '5', '6', '-',
   '1', '2', '3', '+',
   '0', '.', '=',  # 将最后一个=按钮补全空位
]

# 创建并放置按钮
row = 1
col = 0

for button_label in buttons:
   if button_label == "=":
       button = tk.Button(root, text=button_label, width=13, height=2, font=('Arial', 10))
       button.grid(row=row, column=col, columnspan=3, padx=5, pady=5)
       button.bind("<Button-1>", button_click)
   else:
       button = tk.Button(root, text=button_label, width=5, height=2, font=('Arial', 10))
       button.grid(row=row, column=col, padx=5, pady=5)
       button.bind("<Button-1>", button_click)

   col += 1
   if col > 3:
       col = 0
       row += 1

root.mainloop()

